package io.linfeng.common.config;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Configuration
public class NacosRegistrationRegister {
    @Resource
    private NacosDiscoveryProperties nacosDiscoveryProperties;
    //    @Value("${other.ip}")
    private String otherIp = "";

    @PostConstruct
    public void init() throws IOException {
        try {
            URL url = new URL("http://api.ipify.org");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为GET
            connection.setRequestMethod("GET");

            // 设置读取超时和连接超时时间，单位为毫秒
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            String ip = "";
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                ip = in.readLine();
                in.close();
                System.out.println("Public IP Address: " + ip);
            } else {
                System.err.println("Failed to fetch IP. Server returned HTTP code: " + responseCode);
            }

            connection.disconnect();
            nacosDiscoveryProperties.setIp(ip);
            System.out.println(ip);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}